<template>
  <div class="permission-add-container">
    <div class="page-header">
      <div class="header-title">
        <h2>{{ isEdit ? '编辑权限' : '添加权限' }}</h2>
        <span class="subtitle">{{ isEdit ? '修改权限信息' : '创建新的系统权限' }}</span>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>

    <el-card class="form-container" shadow="hover">
      <el-form
        :model="permissionForm"
        :rules="permissionRules"
        ref="permissionFormRef"
        label-width="120px"
        :disabled="loading"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限编码，格式如module:action" />
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型">
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
            <el-option label="接口" value="api" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="路径" prop="path">
          <el-input v-model="permissionForm.path" placeholder="菜单路径或API路径" />
        </el-form-item>
        
        <el-form-item label="上级权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="permissionTree"
            check-strictly
            node-key="id"
            :render-after-expand="false"
            :props="{
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择上级权限"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="permissionForm.sort" :min="0" :max="999" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input v-model="permissionForm.description" type="textarea" :rows="3" placeholder="请输入权限描述" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const permissionFormRef = ref(null);

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.query.id !== undefined;
});

// 权限表单数据
const permissionForm = reactive({
  id: null,
  name: '',
  code: '',
  type: 'menu',
  path: '',
  parentId: null,
  sort: 0,
  description: ''
});

// 权限树数据
const permissionData = ref([
  {
    id: 1,
    name: '小区管理',
    code: 'community:view',
    type: 'menu',
    path: 'property/community',
    description: '小区基本信息管理',
    children: [
      { id: 101, name: '查看小区列表', code: 'community:list', type: 'button', path: '', description: '查看小区列表' },
      { id: 102, name: '添加小区', code: 'community:add', type: 'button', path: '', description: '添加小区信息' },
      { id: 103, name: '编辑小区', code: 'community:edit', type: 'button', path: '', description: '编辑小区信息' },
      { id: 104, name: '删除小区', code: 'community:delete', type: 'button', path: '', description: '删除小区信息' }
    ]
  },
  {
    id: 2,
    name: '房产管理',
    code: 'building:view',
    type: 'menu',
    path: 'property/building',
    description: '楼宇和房产信息管理',
    children: [
      { id: 201, name: '查看栋数列表', code: 'building:list', type: 'button', path: '', description: '查看栋数列表' },
      { id: 202, name: '添加栋数', code: 'building:add', type: 'button', path: '', description: '添加栋数信息' },
      { id: 203, name: '编辑栋数', code: 'building:edit', type: 'button', path: '', description: '编辑栋数信息' },
      { id: 204, name: '删除栋数', code: 'building:delete', type: 'button', path: '', description: '删除栋数信息' },
      { id: 205, name: '查看房产列表', code: 'home:list', type: 'button', path: '', description: '查看房产列表' },
      { id: 206, name: '添加房产', code: 'home:add', type: 'button', path: '', description: '添加房产信息' },
      { id: 207, name: '编辑房产', code: 'home:edit', type: 'button', path: '', description: '编辑房产信息' },
      { id: 208, name: '删除房产', code: 'home:delete', type: 'button', path: '', description: '删除房产信息' }
    ]
  },
  {
    id: 3,
    name: '人员管理',
    code: 'personnel:view',
    type: 'menu',
    path: 'property/personnel',
    description: '业主和车辆信息管理',
    children: [
      { id: 301, name: '查看业主列表', code: 'owner:list', type: 'button', path: '', description: '查看业主列表' },
      { id: 302, name: '添加业主', code: 'owner:add', type: 'button', path: '', description: '添加业主信息' },
      { id: 303, name: '编辑业主', code: 'owner:edit', type: 'button', path: '', description: '编辑业主信息' },
      { id: 304, name: '删除业主', code: 'owner:delete', type: 'button', path: '', description: '删除业主信息' },
      { id: 305, name: '查看车辆列表', code: 'vehicle:list', type: 'button', path: '', description: '查看车辆列表' },
      { id: 306, name: '添加车辆', code: 'vehicle:add', type: 'button', path: '', description: '添加车辆信息' },
      { id: 307, name: '编辑车辆', code: 'vehicle:edit', type: 'button', path: '', description: '编辑车辆信息' },
      { id: 308, name: '删除车辆', code: 'vehicle:delete', type: 'button', path: '', description: '删除车辆信息' }
    ]
  },
  {
    id: 4,
    name: '车位管理',
    code: 'parking:view',
    type: 'menu',
    path: 'property/parking',
    description: '车位和使用记录管理',
    children: [
      { id: 401, name: '查看车位列表', code: 'parking:list', type: 'button', path: '', description: '查看车位列表' },
      { id: 402, name: '添加车位', code: 'parking:add', type: 'button', path: '', description: '添加车位信息' },
      { id: 403, name: '编辑车位', code: 'parking:edit', type: 'button', path: '', description: '编辑车位信息' },
      { id: 404, name: '删除车位', code: 'parking:delete', type: 'button', path: '', description: '删除车位信息' },
      { id: 405, name: '查看使用记录', code: 'parking:usage:list', type: 'button', path: '', description: '查看车位使用记录' },
      { id: 406, name: '添加使用记录', code: 'parking:usage:add', type: 'button', path: '', description: '添加车位使用记录' },
      { id: 407, name: '编辑使用记录', code: 'parking:usage:edit', type: 'button', path: '', description: '编辑车位使用记录' },
      { id: 408, name: '删除使用记录', code: 'parking:usage:delete', type: 'button', path: '', description: '删除车位使用记录' }
    ]
  },
  {
    id: 5,
    name: '服务管理',
    code: 'service:view',
    type: 'menu',
    path: 'property/service',
    description: '活动、报修、投诉和信箱管理',
    children: [
      { id: 501, name: '查看活动列表', code: 'activity:list', type: 'button', path: '', description: '查看活动列表' },
      { id: 502, name: '添加活动', code: 'activity:add', type: 'button', path: '', description: '添加活动信息' },
      { id: 503, name: '编辑活动', code: 'activity:edit', type: 'button', path: '', description: '编辑活动信息' },
      { id: 504, name: '删除活动', code: 'activity:delete', type: 'button', path: '', description: '删除活动信息' },
      { id: 505, name: '查看报修列表', code: 'repair:list', type: 'button', path: '', description: '查看报修列表' },
      { id: 506, name: '处理报修', code: 'repair:process', type: 'button', path: '', description: '处理报修请求' },
      { id: 507, name: '查看投诉列表', code: 'complaint:list', type: 'button', path: '', description: '查看投诉列表' },
      { id: 508, name: '处理投诉', code: 'complaint:process', type: 'button', path: '', description: '处理投诉请求' },
      { id: 509, name: '查看信箱列表', code: 'mailbox:list', type: 'button', path: '', description: '查看信箱列表' },
      { id: 510, name: '回复信箱', code: 'mailbox:reply', type: 'button', path: '', description: '回复信箱消息' }
    ]
  },
  {
    id: 6,
    name: '系统管理',
    code: 'system:view',
    type: 'menu',
    path: 'system',
    description: '用户、角色和权限管理',
    children: [
      { id: 601, name: '查看用户列表', code: 'user:list', type: 'button', path: '', description: '查看用户列表' },
      { id: 602, name: '添加用户', code: 'user:add', type: 'button', path: '', description: '添加用户信息' },
      { id: 603, name: '编辑用户', code: 'user:edit', type: 'button', path: '', description: '编辑用户信息' },
      { id: 604, name: '删除用户', code: 'user:delete', type: 'button', path: '', description: '删除用户信息' },
      { id: 605, name: '查看角色列表', code: 'role:list', type: 'button', path: '', description: '查看角色列表' },
      { id: 606, name: '添加角色', code: 'role:add', type: 'button', path: '', description: '添加角色信息' },
      { id: 607, name: '编辑角色', code: 'role:edit', type: 'button', path: '', description: '编辑角色信息' },
      { id: 608, name: '删除角色', code: 'role:delete', type: 'button', path: '', description: '删除角色信息' },
      { id: 609, name: '查看权限列表', code: 'permission:list', type: 'button', path: '', description: '查看权限列表' },
      { id: 610, name: '权限配置', code: 'permission:config', type: 'button', path: '', description: '配置权限信息' }
    ]
  }
]);

// 计算属性：权限树形结构（用于选择上级权限）
const permissionTree = computed(() => {
  // 添加一个根节点选项
  return [
    { id: 0, name: '根权限', children: permissionData.value }
  ];
});

// 表单验证规则
const permissionRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-z]+:[a-z]+(:?[a-z]+)?$/, message: '权限编码格式应为module:action', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
};

// 初始化
onMounted(async () => {
  if (isEdit.value) {
    await fetchPermissionData();
  }
});

// 获取权限数据
const fetchPermissionData = async () => {
  const permissionId = route.query.id;
  if (!permissionId) return;
  
  loading.value = true;
  try {
    // 模拟API调用
    // const token = localStorage.getItem('token');
    // const response = await axios.get(`/api/permissions/${permissionId}`, {
    //   headers: { Authorization: `Bearer ${token}` }
    // });
    
    // 填充表单
    // const permissionData = response.data;
    
    // 模拟数据 - 查找权限
    const findPermission = (permissions, id) => {
      for (const permission of permissions) {
        if (permission.id === parseInt(id)) {
          return permission;
        }
        if (permission.children) {
          const found = findPermission(permission.children, id);
          if (found) return found;
        }
      }
      return null;
    };
    
    const permission = findPermission(permissionData.value, parseInt(permissionId));
    
    if (permission) {
      permissionForm.id = permission.id;
      permissionForm.name = permission.name;
      permissionForm.code = permission.code;
      permissionForm.type = permission.type;
      permissionForm.path = permission.path || '';
      
      // 查找父节点
      const findParentId = (permissions, childId) => {
        for (const permission of permissions) {
          if (permission.children) {
            if (permission.children.some(child => child.id === childId)) {
              return permission.id;
            }
            const found = findParentId(permission.children, childId);
            if (found) return found;
          }
        }
        return null;
      };
      
      permissionForm.parentId = findParentId(permissionData.value, permission.id);
      permissionForm.sort = permission.sort || 0;
      permissionForm.description = permission.description || '';
    } else {
      ElMessage.error('未找到权限数据');
      goBack();
    }
  } catch (error) {
    console.error('获取权限数据失败:', error);
    ElMessage.error('获取权限数据失败');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!permissionFormRef.value) return;
  
  await permissionFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.value = true;
    try {
      // 准备提交的数据
      const submitData = { ...permissionForm };
      
      // 模拟API调用
      // const token = localStorage.getItem('token');
      // const headers = { Authorization: `Bearer ${token}` };
      
      if (isEdit.value) {
        // 更新权限
        // await axios.put(`/api/permissions/${permissionForm.id}`, submitData, { headers });
        ElMessage.success('权限更新成功');
      } else {
        // 创建权限
        // await axios.post('/api/permissions', submitData, { headers });
        ElMessage.success('权限创建成功');
      }
      
      // 返回列表页
      goBack();
    } catch (error) {
      console.error('保存权限失败:', error);
      ElMessage.error('保存权限失败: ' + (error.response?.data?.message || error.message));
    } finally {
      loading.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  permissionFormRef.value?.resetFields();
};

// 返回列表页
const goBack = () => {
  router.push('/system/permission');
};
</script>

<style scoped>
.permission-add-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.form-container .el-form {
  padding: 20px 0;
}
</style> 